/**
 * 登录模块，提供登录相关业务功能
 * 
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "sysmanMain","msgServ", "ajaxServ","datagridServ","bizProto","btnServ","formServ"],
		function($,main, msgServ, ajaxServ,datagridServ,bizProto,btnServ,formServ) {

			'use strict';

			//根节点定义
			var rootid = 'panel-flowTaskConfig'
			
			//弹窗定义
			var window_id = 'roleEdit-win'
			
			var baseLeftQueryUrl,baseRightByLeftIdQueryUrl,flowNodeUrl;
			
			var flowConfig = {				
				"id":"oaSeniorTitleAppointment:1:92568",
				"name":"高级职称聘任",
				"key":"oaSeniorTitleAppointment",
				"category":"http://www.activiti.org/processdef",
				"description":null,"version":1,
				"resourceName":"oaSeniorTitleAppointment.bpmn20.xml",
				"deploymentId":"92565",
				"deploymentTime":null,
				"diagramResourceName":"oaSeniorTitleAppointment.oaSeniorTitleAppointment.png",
				"startFormKey":null,
				"suspended":false,"tenantId":""			
			}
			
			//表单配置
			var formConfig = {
				procDefinitionId: null, //流程定义编码
				procDefinitionName: null, //流程定义名称
				activityId		: null,	//流程节点ID
				activityName	: null, //流程节点名称
				activityType	: null, //activityType
				bizname			: null, //业务名称
				fullBizcode 	: null, //完整业务编码
				activityConfig  : null,  //节点配置
				
				role			: null,	//系统角色id，可配置多个，逗号分隔
				job_role		: null, //岗位角色id，可配置多个，逗号分隔
				title_role		: null, //头衔角色id，可配置多个，逗号分隔						
				dept			: null, //科室，可直接填写科室id，或科室id所对应字段名称
				user			: null,	//用户，可直接填写用户id，或用户id所对应字段名称
				direct			: null,	//科室主管领导(按照科室主管领导设置进行查找，可填写科室所在字段名称)
				requiredFilter	: null,	//表单必填字段
				editableFilter	: null,	//表单可编辑字段
				archiveEnabled	: null,	//表单启用附件编辑
				subEnable		: null	//启用子表
			}	
			//流程节点定义值json配置
			var nodeConfig = {
				roleUserFilter	: {
					role		: null,	//系统角色id，可配置多个，逗号分隔
					job_role	: null, //岗位角色id，可配置多个，逗号分隔
					title_role	: null, //头衔角色id，可配置多个，逗号分隔
					user		: null	//用户，直接配置用户id，该项配置可被fieldFilter同名项替代
				}
				,
				fieldFilter		: {
					dept		: null, //科室，可直接填写科室id，或科室id所对应字段名称
					user		: null	//用户，可直接填写用户id，或用户id所对应字段名称
				}
				,
				leader			: {
					direct		: null	//科室主管领导(按照科室主管领导设置进行查找，可填写科室所在字段名称)
				}
				,
				requiredFilter	: null,	//表单必填字段
				editableFilter	: null,	//表单可编辑字段
				archiveEnabled	: null,	//表单启用附件编辑
				subEnable		: null	//启用子表
			}
			
			var layerConfig = {
				list	: 'list',	//节点列表页面
				node	: 'node'	//节点明细页面
			}
			//缺省层级定义
			var defaultLayer = {
				layer	: null,
				flow	: null,	//当前流程
				node	: null	//当前节点
			}
			
			//当前层级定义
			var currentLayer = {
				layer	: null,
				flow	: null,	//当前流程
				node	: null	//当前节点
			}
				
				

			var private_method = {
				
				//初始化流程列表
				initList : function(doc) {
					if (window.console) {
					console.info('flowTaskConfig modules gets ready and been loaded.');
					}
					var _bizProto = new bizProto({doc:doc,rootId:'panel-flowTaskConfig',panelSelector:'div.well',subSystemCode:'workflow',moduleCode:'flowTaskConfig'});
					_bizProto.gridHeight -= 15;
					
					var _buttonConfig={
						
						 "保存":private_method.save,
						 "新增":private_method.add,
						 "删除":private_method.remove,
						 "刷新缓存":private_method.reload
						 							
					}
					private_method.initPath();
					
					var $flowList = $('#' + rootid + ' .dg-flowList');
					
					var $flowListGrid = $flowList.datagrid({
						title		: '流程信息',
						height 		: _bizProto.gridHeight,
						url 		: baseLeftQueryUrl,	
						rownumbers	: true,
						animate		: true,							
						striped		: true,
						border		: true,
						//singleSelect:false,
						idField		: 'id',
						pagination 	: true,								
						fitColumns	: true,
						//onClickRow:function(rowIndex, rowData){private_method.getPermission(rowIndex, rowData)}
						onDblClickRow : private_method.getFlowConfig,
						columns		: [[
							{field:'ck',checkbox:"true"},        
							{field:'name',title:'流程名称',halign:'center',width:30},        
							{field:'version',title:'版本号',width:30,align:'center',halign:'center'}
						]]
					});
	
					var $activityList = $('#'+ rootid + ' .dg-activityList');
					
					
					var bizFlowListUrl = _bizProto.rootPath + '/permission/query/getFlowList.action'
					
					var activity_type_url = _bizProto.rootPath + '/dictionary/getTree.action?id=' + 115
					var $activityListGrid=	$activityList.datagrid({
						title		: '节点配置',
						url 		: baseRightByLeftIdQueryUrl,
						height 		: _bizProto.gridHeight,
						rownumbers	: true,
						animate		: true,										
						striped		: true,
						singleSelect: true,
						border		: true,					
						idField		: 'id',										
						fitColumns	: true,
						onDblClickRow:private_method.getNodeConfig,
						columns		: [[
							{field:'ck',checkbox:"true"},        
							{field:'activityId',title:'节点ID',halign:'center',width:30},        
							{field:'activityName',title:'节点名称',width:30,align:'center',halign:'center'},
							{field:'activityType',title:'节点类型',width:30,align:'center',halign:'center'},
							{field:'sortedid',title:'排序编号',width:30,align:'center',halign:'center',editor:'text'},
							{field:'bizname',title:'业务名称',width:30,halign:'center'},        
							{field:'fullBizcode',title:'业务编码',width:30,align:'right',halign:'center'},
							{field:'activityConfig',title:'流程配置',width:100,align:'right',halign:'center',editor:'text'}
						]],
						rowStyler	: function(index,row){   
					        if (row.state){					        	
				        	 	if (row.state<0){
				        			return 'background-color:pink;';				        			
					        	}
					        }   
					    },					    
						toolbar		: '#' + rootid + ' #tb-activityList'
					})	
					
					private_method.bindBtnEvent()
					
					
					$.messager.progress('close');
					
				},
				
				//初始化路径
				initPath:function(){					
					baseLeftQueryUrl = '/'+main.getRootPath() +
						'/flowDefinition/getLastVersionListDomain.action';
					
					
					baseRightByLeftIdQueryUrl = '/'+main.getRootPath() +
						'/flowTaskConfig/getLackDefinition.action';
						
					flowNodeUrl ='/'+main.getRootPath() +'/flowDefinition/getTaskDefinitions.action'
					
				},
				//初始化编辑页面元素
				initEdit:function(_options){
					// 编辑窗口初始化					
					var editTd = $('#' +window_id + ' .edit-btn')
					var _fullBizcode = main.getCurrentBizcode();
//					if(editTd && editTd.length>0){
//						var _param = {
//							bizcode:_fullBizcode,
//							rootPath:'/'+main.getRootPath(),
//							container:editTd,
//							callback:private_method.bindEditEvent}
//						btnServ.generateEditBtn(_param);
//					}
					
					var _form = $('#' + window_id + ' .main-form');
					
					_form.form('clear');
					_form.form('load',private_method.initData());
					private_method.bindEditEvent();
				},
				//根据左侧点击事件更新右侧流程节点列表信息
				getFlowConfig:function(rowIndex,rowData){
					if(rowData){
						if(rowData.id){
							//选中点击行
							var $flowList = $('#' + rootid + ' .dg-flowList');
							$flowList.datagrid('clearSelections')
								.datagrid('selectRow',rowIndex)
								.datagrid('checkRow',rowIndex);
							//刷新节点列表
							var $activityList = $('#'+ rootid + ' .dg-activityList');
							$($activityList).datagrid('reload',{procDefinitionId:rowData.id})
							currentLayer.flow = rowData;
							currentLayer.node = null;
						}
					}					
				},
				
				//根据双击事件弹窗显示选中节点信息
				getNodeConfig:function(rowIndex,rowData){
					if(rowData && rowData.id){
						
						var $nodeList = $('#'+ rootid + ' .dg-activityList');
						$nodeList.datagrid('clearSelections')
							.datagrid('selectRow',rowIndex)
							.datagrid('checkRow',rowIndex);
						currentLayer.node = rowData;
						/**
						 * 弹窗显示编辑页面
						 */
						public_method.openPage();
					}else{
						msgServ.Msgslide('节点尚未保存，请保存后再执行操作');
					}
				},
				
				//绑定按钮事件
				bindBtnEvent:function(){
					
					var window_btn = $('#' + rootid +' .function-btn')
					$(window_btn).unbind('click')
					$(window_btn).bind('click',	
						function(e){
							btnServ.applyBtnCode({buttonEvt:e,buttonConfig:btnEvent})
						}
					)
				}
				,
				bindEditEvent : function(){
					var window_btn = $('#' + window_id +' .function-btn')
					$(window_btn).unbind('click')
					$(window_btn).bind('click',	
						function(e){
							btnServ.applyBtnCode({buttonEvt:e,buttonConfig:btnEvent})
						}
					)
				}
				,
				closePage:function(){
					currentLayer.node = null;
					$('#'+window_id).empty();
				}
				,
				/**
				 * 根据获取的配置信息在页面显示
				 */
				initData:function(){					
					var _data	,_nodeConfig
					
					if(currentLayer){
						if(currentLayer.node){						
					
							_data = currentLayer.node;
							_data.procDefinitionName = currentLayer.flow.name;
							if(_data.activityConfig){
								_nodeConfig = $.evalJSON(_data.activityConfig)
								if(_nodeConfig){
									if(_nodeConfig.roleUserFilter){
										_data.role = _nodeConfig.roleUserFilter.role;
										_data.job_role = _nodeConfig.roleUserFilter.job_role;
										_data.title_role = _nodeConfig.roleUserFilter.title_role;
									}
									if(_nodeConfig.fieldFilter){
										_data.user = _nodeConfig.fieldFilter.user;
										_data.dept = _nodeConfig.fieldFilter.dept;
										_data.defaultUserid = _nodeConfig.fieldFilter.defaultUserid;
									}
									if(_nodeConfig.leader)
										_data.direct = _nodeConfig.leader.direct;									
									
									_data.requiredFilter = _nodeConfig.requiredFilter;
									_data.editableFilter = _nodeConfig.editableFilter;
									_data.variableFilter = _nodeConfig.variableFilter;									
									_data.archiveEnabled = _nodeConfig.archiveEnabled;
									_data.subEnable = _nodeConfig.subEnable;
								}
							}else{
								if(currentLayer.flow){
									flowConfig = currentLayer.flow;
									_data.procDefinitionId = flowConfig.id;
									_data.procDefinitionName = flowConfig.name;
								}
							}
						}
					}
					
					if(!_data.bizcode){
						$.ajax({
							url		: '/'+main.getRootPath()+'/permission/query/getOneByField.action',
							data	: {field : 'flowid',fieldVal : _data.procDefinitionId},
							async	: false,
							success : function(data){
								_data.fullBizcode = data.fullBizcode;
								_data.bizname = data.name;
							}
							,
							error	: function(){
								msgServ.Msgslide('获取业务信息失败，请刷新后尝试，如问题依旧，请联系系统管理员进行处理');
							}
						})
					}
					return _data;						
				}
				,
				/**
				 * 封装数据
				 */
				enData:function(){
					
					var _data;
					
					var _nodeConfig ={};
					
					var _form = $('#' + window_id + ' .main-form')
					
					if(_form.length==1){
						var formData = formServ.getDataObj({
							form : $(_form)
						});
						
						_data = formData;
						
						//流程节点角色配置判断
						var ruf = {};
						if(_data.role){
							ruf.role = _data.role	
						}
						
						if(_data.job_role){
							ruf.job_role = _data.job_role
						}
						
						if(_data.title_role){
							ruf.title_role = _data.title_role
						}
						
						if(!$.isEmptyObject(ruf)){
							_nodeConfig.roleUserFilter = ruf
						}
						
						//节点部门及人员配置判断
						var ff = {}
						if(_data.user){
							ff.user = _data.user;
						}
						
						if(_data.dept){
							ff.dept = _data.dept;
						}
						
						if(_data.defaultUserid){
							ff.defaultUserid = _data.defaultUserid;	
						}
						
						if(!$.isEmptyObject(ff)){
							_nodeConfig.fieldFilter = ff
						}
						
						//科室主管领导配置
						if(_data.direct){
							_nodeConfig.leader = {direct:_data.direct}
						}
						//必填字段配置
						if(_data.requiredFilter){
							_nodeConfig.requiredFilter = _data.requiredFilter
						}
						
						//可填字段配置
						if(_data.editableFilter){
							_nodeConfig.editableFilter = _data.editableFilter
						}
						
						//附件启用配置
						if(_data.archiveEnabled){
							_nodeConfig.archiveEnabled = _data.archiveEnabled
						}
						//节点变量配置
						if(_data.variableFilter){
							_nodeConfig.variableFilter = _data.variableFilter
						}
						
						//子表启用配置
						if(_data.subEnable){
							_nodeConfig.subEnable = _data.subEnable
						}						
						
						_data.activityConfig = $.toJSON(_nodeConfig);
					}
					
					return _data;
					
				}
				,
				reloadActivity:function(e){
					if(currentLayer && currentLayer.flow && currentLayer.flow.id){
						var _grid = $('#' + rootid + ' .dg-activityList');
						_grid.datagrid('reload',{procDefinitionId:currentLayer.flow.id})
					}
					
					if(e && e.currentTarget){
						$(e.currentTarget).linkbutton('enable')
					}
				}
				
			}			
			
			var btnEvent = {
				//功能按钮监听函数
				listSave:function(e){
					
					var $activityListGrid = $('#' + rootid + ' .dg-activityList');
					
					var _data = $($activityListGrid).datagrid('getData')
					if(_data && _data.rows){
						//save data to remote
						
						var _url = '/'+main.getRootPath()  + '/flowTaskConfig/saveList.action'
						$.ajax({
							url:_url,
							type : 'post',
							dataType:'json',
							data:$.toJSON(_data.rows),
							contentType:'appliction/json;charset=utf-8',						
							success:function(data){
								msgServ.Msgslide('操作成功');
								private_method.reloadActivity(e);
							}
							,
							error:function(){
								msgServ.Msgslide('操作失败');
								if(e && e.currentTarget){
									$(e.currentTarget).linkbutton('enable')
								}
							}
						})
					}					
				},
				listAdd:function(e){
					if(!currentLayer.flow || !currentLayer.flow.id){
						msgServ.Msgslide('请选择流程节点');						
					}else{
						currentLayer.node = null;
						public_method.openPage();
					}
					
					if(e && e.currentTarget){
						$(e.currentTarget).linkbutton('enable')
					}
				},
				
				listRemove:function(e){
					
					var $grid = $('#' + rootid + ' .dg-activityList');
					datagridServ.delRow({
						url		: '/'+main.getRootPath()+'/flowTaskConfig/del.action',
						target	: $grid,
						evt		: e
					});
				},
				
				listReload:function(e){
					$.ajax({
						url:'/'+main.getRootPath() +'/flowTaskConfig/query/reloadConfig.action',
						success:function(data){
							msgServ.Msgslide('刷新缓存成功');
							if(e && e.currentTarget){
								$(e.currentTarget).linkbutton('enable')
							}
						}
						,
						error:function(){
							msgServ.Msgslide('刷新缓存失败');
							if(e && e.currentTarget){
								$(e.currentTarget).linkbutton('enable')
							}
						}
					})
				}
				,
				editSave:function(e){
					var data = private_method.enData();
					$.ajax({
						url			: '/'+main.getRootPath()+'/flowTaskConfig/save.action',
						data		: $.toJSON(data),
						dataType	: 'json',
						contentType : "appliction/json;charset=utf-8",
						type		: 'post',
						success		: function(data){
							msgServ.Msgslide('操作成功');
							private_method.reloadActivity(e);
							
							var _form = $('#' + window_id + ' .main-form')
							currentLayer.node = data
							var _data = private_method.initData();
							_form.form('load',_data);
						}
						,
						error		:function(){
							msgServ.Msgslide('操作失败');
							if(e && e.currentTarget){
								$(e.currentTarget).linkbutton('enable')
							}
						}
					})
				}
				,
				editAdd:function(e){
					
				}
				,
				editRemove:function(e){
					
				}
				,
				editCancel:function(e){
					$('#' + window_id).window('close');
				}
			}
			var public_method = {
				//初始化列表页面
				initList:function(doc){
					private_method.initList(doc)
				}
				,
				//初始化编辑页面
				initEdit:function(_options){
					private_method.initEdit();
				}
				,
				/**
				 * 脚本弹窗
				 */
				openPage:function(_options){
					var _url = '/'+main.getRootPath()+ '/flowTaskConfig/query/editPage.action'
					var config = {
						title	: '流程节点设置',
						href	: _url,
						window	: $('#' + window_id),
						width	: '900',
						height	: '700',
						flag	: false,
						onClose : private_method.closePage
					}					
					var _param = $.extend({},config,_options)
					datagridServ.windowEditCenter(_param);
				}
			};

			return public_method;

		});